import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import {ElLoading} from 'element-plus'
// import router from '@/router/IndexRouter'
import {  err } from '@/utils/ele'
import store from '@/store/IndexStore'
import {MUTION} from '@/utils/common'

let loading;
const loadingStart = ():void => {
  const option = {
    lock : true,
    text: '加载中...',
    target: '.loading-box',
    background: 'rgb(250,250,250,.9)',
  }
  loading = ElLoading.service(option)
}
const loadingEnd = ():void  => {
  loading && loading.close();
}
const pending = []; //声明一个数组用于存储每个请求的取消函数和axios标识
const cancelToken = axios.CancelToken;
const removePending = (config) => {
  // console.log('axios config ',config);
  for (const i in pending) {
    if (pending[i].url === config.url) { //在当前请求在数组中存在时执行取消函数
      console.log('axios cancel ',config.url);
      loadingEnd();
      pending[i].f(); //执行取消操作
      //pending.splice(i, 1); 根据具体情况决定是否在这里就把pending去掉
      console.log(pending[i].url);
    }
  }
}
// 请求拦截
axios.interceptors.request.use((config: AxiosRequestConfig) => {
  removePending(config); //在一个axios发送前执行一下判定操作，在removePending中执行取消操作
  // console.log(config.url);
  config.cancelToken = new cancelToken(function executor(c) {//本次axios请求的配置添加cancelToken
    pending.push({
      // url: config.url,
      url: axios.defaults.baseURL + config.url,
      f: c
    });
  })
  config.headers.Accept = 'application/json'
  const sid = (store.state.isLogin && store.state.uinfo) ? store.state.uinfo.sid : ''
  config.headers.JWT =  sid
  config.timeout = 3000
  console.log('req',config)
  loadingEnd()
  loadingStart()
  return config
})
// 响应拦截
axios.interceptors.response.use((rsp: AxiosResponse) => {
  removePending(rsp.config);
  let ret:RSP_200 = null;
  console.log('inter rsp', rsp)
  if(rsp && rsp.status == 200){
    ret = rsp.data;
    // console.log('http ',rsp.ret);
    if(ret.code){
      // 4116 需要登录
      // 4016 立即登陆
      if (ret.code == 4016 || ret.code == 4116) {
        err('请重新登录 ... , 3秒后前往登陆')
        // console.log('请先登录')
        setTimeout(() => {
          store.commit(MUTION.LOGOUT)
        //   router.push('/login')
        }, Math.max(ret.delay,3000));
      }else{
        err(`${ret.code} : ${ret.msg} `)
        console.log('服务出错 ...',ret.msg)
      }
    }
  }else{
    err('请求出错 ...')
    console.log('请求出错 ...',rsp)
  }
  loadingEnd()
  return ret
},err => {
  loadingEnd();
  return Promise.reject(err)
})

declare type RSP_200 = {
  code: number,
  msg: string,
  data: [],
  count?: number,
  delay?: number,
  time?: number
  url?: string,
}

export default axios